package br.ufc.cloud.qnotes.ui;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;

import com.example.qnotes.R;

public class MainActivity extends Activity {
	EditText note;
	EditText title;
	ImageView image;
	String pathImg;
	String nomeImg;
	private static int RESULT_LOAD_IMAGE = 1;
	private static int CAMERA_RESULT = 1337;
	
	private Uri imagePathUri;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		image = (ImageView)findViewById(R.id.imageViewNote);
		note = (EditText) findViewById(R.id.editText1);
		title = (EditText)findViewById(R.id.editText2);

	}
	
	public String getUriFromBlob() throws IOException, XmlPullParserException{
		
		String name = nomeImg;
		
		SoapObject soap = new SoapObject("http://dao.service.cloud.ufc.br","getUriFromBlob");
		soap.addProperty("nameImg", name);
		
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
				SoapEnvelope.VER11);
		envelope.setOutputSoapObject(soap);

		Log.i("NGVL", "Chamando NoteDAO");

		String url = "http://localhost:8080/QNotesWebService/services/NoteDAO";

		HttpTransportSE httptransport = new HttpTransportSE(url);
			httptransport.call("", envelope);

			Object msg = envelope.getResponse();

			Log.i("NGVL", "Mensagem:" + msg);
		
		Object resultado = envelope.getResponse();
		
		return resultado.toString();
	}
	
	public void uploadImage() throws IOException, XmlPullParserException{
		String path = pathImg;
		String name = nomeImg;
		
		SoapObject soap = new SoapObject("http://dao.service.cloud.ufc.br","uploadImage");
		soap.addProperty("pathImg", path);
		soap.addProperty("nameImg", name);
		
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
				SoapEnvelope.VER11);
		envelope.setOutputSoapObject(soap);

		Log.i("NGVL", "Chamando NoteDAO");

		String url = "http://localhost:8080/QNotesWebService/services/NoteDAO";

		HttpTransportSE httptransport = new HttpTransportSE(url);

			httptransport.call("", envelope);

			Object msg = envelope.getResponse();

			Log.i("NGVL", "Mensagem:" + msg);
		
		
	}

	public void createNote() throws IOException, XmlPullParserException {
		String notes = note.getText().toString();
		SoapObject soap = new SoapObject("http://dao.service.cloud.ufc.br","createNote");
		soap.addProperty("note", notes);
		soap.addProperty("pathBlob", getUriFromBlob());
		soap.addProperty("pathSQLite", pathImg);
		soap.addProperty("title", title.toString());

		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
				SoapEnvelope.VER11);
		envelope.setOutputSoapObject(soap);

		Log.i("NGVL", "Chamando NoteDAO");

		String url = "http://localhost:8080/QNotesWebService/services/NoteDAO";

		HttpTransportSE httptransport = new HttpTransportSE(url);

			httptransport.call("", envelope);

			Object msg = envelope.getResponse();

			Log.i("NGVL", "Mensagem:" + msg);
	}
	
	public ArrayList<Nota> getNotas(){
		
		ArrayList<Nota> notes = new ArrayList<Nota>();
		
		SoapObject soap = new SoapObject("http://dao.service.cloud.ufc.br","getNotes");
		
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
				SoapEnvelope.VER11);
		
		envelope.setOutputSoapObject(soap);

		Log.i("NGVL", "Chamando NoteDAO");

		String url = "http://localhost:8080/QNotesWebService/services/NoteDAO";

		HttpTransportSE httptransport = new HttpTransportSE(url);
			try {
				httptransport.call("", envelope);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (XmlPullParserException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		
		SoapObject results = (SoapObject)envelope.bodyIn;
		
		int count = results.getPropertyCount();
		
		for (int i=0; i< count; i++){
			Nota nota = new Nota();
			SoapObject obj = (SoapObject)results.getProperty(i);
			SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
			Date date = new Date();
			try {
				date = (Date)formatter.parse(obj.getProperty("data").toString());
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			nota.setData(date);
			nota.setPathBlob(obj.getProperty("pathBlob").toString());
			nota.setPathSQL(obj.getProperty("pathSQL").toString());
			nota.setText(obj.getProperty("text").toString());
			nota.setTitle(obj.getProperty("title").toString());
			notes.add(nota);
		}
		return notes;
	}

	private class Task extends AsyncTask<Void, Void, Void> {

		@Override
		protected Void doInBackground(Void... params) {
			try {
				createNote();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (XmlPullParserException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
		}

	}

	public void onClickSaveNote(View view) {
		Task t = new Task();
		t.execute();
	}

	public void run() {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data){
		if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data){
			
			Uri selectedImage = data.getData();
			String[] filePathColum = {MediaStore.Images.Media.DATA};
			
			Cursor cursor = getContentResolver().query(selectedImage, filePathColum, null, null, null);
			cursor.moveToFirst();
			int columnIndex = cursor.getColumnIndex(filePathColum[0]);
			String picturePath = cursor.getString(columnIndex);
			cursor.close();
			
			ImageView img = (ImageView)findViewById(R.id.imageViewNote);
			img.setImageBitmap(BitmapFactory.decodeFile(picturePath));
		}
		
		if(requestCode == CAMERA_RESULT && resultCode == RESULT_OK){
			Bitmap bitmap = (Bitmap)data.getExtras().get("data");
			ImageView img = (ImageView)findViewById(R.id.imageViewNote);
			img.setImageBitmap(bitmap);
			pathImg = imagePathUri.getPath();
			File file = new File(imagePathUri.getPath());
//			bitmap.compress(Bitmap.CompressFormat.JPEG, 150, file);
//			String delimiter = "\\.";
//			String[] s = (imagePathUri.getPath()).split(delimiter);
			nomeImg = file.getName();
			
		}
		
	}
	
	public void callgalery(){
			Intent i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
	         
	        startActivityForResult(i, RESULT_LOAD_IMAGE);
	    }
	
	public void callcamera(){
		Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
		i.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, imagePathUri);
        startActivityForResult(i, CAMERA_RESULT);
    }
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item){
		
		switch (item.getItemId()) {
		case R.id.gallery_main:
			callgalery();
			
			break;
			
		case R.id.camera_main:
			callcamera();
			
			break;

		default:
			break;
		}
		
		return false;
	}

}
